﻿#include "baseframe.h"
using namespace IGBTProtocol;

BaseFrame::BaseFrame()
{
    _frameHeader = FrameHeader_Undef;
    _dataSize = 0;
    _crc = 0;
}

BaseFrame::BaseFrame(FrameHeaderType frameHeader, unsigned int dataSize)
{
    _frameHeader = frameHeader;
    _dataSize = dataSize;
    _crc = 0;
}

BaseFrame::~BaseFrame()
{

}

unsigned char BaseFrame::calcCRC(QByteArray* buff, unsigned int size)
{
    unsigned char crc = 0;
    unsigned int i=0;
    while(i < size)
    {
        crc += *((unsigned char*)(buff->data() + i));
        i++;
    }

    return crc;
}

FrameHeaderType BaseFrame::judge(QByteArray* buff)
{
    unsigned short cmd = (unsigned char)(buff->at(0));
    cmd <<= 8;
    cmd += (unsigned char)(buff->at(1));
    if (cmd == FrameHeader_Cmd)
        return FrameHeader_Cmd;
    else if(cmd == FrameHeader_Data)
        return FrameHeader_Data;
    else return FrameHeader_Undef;
}

bool BaseFrame::depack(QByteArray* buff)
{
    _dataSize = (unsigned char)(buff->at(8));
    _dataSize <<= 8;
    _dataSize += (unsigned char)(buff->at(7));
    _dataSize <<= 8;
    _dataSize += (unsigned char)(buff->at(6));
    _dataSize <<= 8;
    _dataSize += (unsigned char)(buff->at(5));

    unsigned int len = buff->length();
    if (calcCRC(buff, len - 1) != (unsigned char)(buff->at(len-1)))
        return false;

    return true;
}

unsigned int BaseFrame::frame(QByteArray* buff, bool tail)
{
    buff->append(_frameHeader >> 8);
    buff->append(_frameHeader & 0x00ff);

    buff->append((char)0);
    buff->append((char)0);
    buff->append((char)0);

    buff->append(_dataSize & 0x000000ff);
    buff->append((_dataSize >> 8) & 0x000000ff);
    buff->append((_dataSize >> 16) & 0x000000ff);
    buff->append((_dataSize >> 24) & 0x000000ff);

    if(!tail)
        return 9;

    for(unsigned int i=0;i<_dataSize;i++)
        buff->append((char)0);

    buff->append(calcCRC(buff,_dataSize + 7));
    return 10+_dataSize;
}
